﻿using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Common;
using SlimDX;
using StillDesign;

namespace Editor
{
    public delegate void ApplicationIdleEventHandler(float elapsedTime);
    
    static class Program
    {
        public static event ApplicationIdleEventHandler ApplicationIdle;

        private static Stopwatch m_Clock;

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            m_Clock = Stopwatch.StartNew();

            Application.Idle += new EventHandler(Application_OnIdle);
            Application.Run(new EditorWindow());

            foreach (SlimDX.ComObject item in SlimDX.ObjectTable.Objects)
                item.Dispose();
            //foreach (StillDesign.PhysX.Actor actor in PhysicsUtils.PhysXScene.Actors)
            //    actor.Dispose();
            //PhysicsUtils.PhysXScene.Dispose();
            PhysicsUtils.PhysXCore.Dispose();
        }

        private static bool IsApplicationIdle
        {
            get
            {
                Common.NativeMethods.NativeMessage msg;
                return !Common.NativeMethods.PeekMessage(out msg, new HandleRef(), 0, 0, 0);
            }
        }

        static void Application_OnIdle(object sender, EventArgs e)
        {
            while ((Form.ActiveForm != null) && IsApplicationIdle)
            {
                if (ApplicationIdle != null)
                {
                    float elapsedTime = (float)m_Clock.ElapsedTicks / (float)Stopwatch.Frequency;
                    m_Clock.Reset();
                    m_Clock.Start();

                    ApplicationIdle(elapsedTime);
                }
            }
        }
    }
}
